'use strict';

const Controller = require('egg').Controller;
const fs = require('mz/fs');
const path = require('path');
class CommonController extends Controller {
  // 上传
  async upload() {
    const ctx = this.ctx;

    if (!ctx.request.files) {
      return ctx.fail('请先选择上传文件');
    }

    const file = ctx.request.files[0];
    const name = 'boyi-oss/' + ctx.genID(10) + path.extname(file.filename);
    let result;
    try {
      result = await ctx.oss.put(name, file.filepath);
    } catch (err) {
      ctx.fail(err);
      console.log(err);
    } finally {
      await fs.unlink(file.filepath);
    }

    if (result) {
      return ctx.success(result.url);
    }

    ctx.fail('上传失败');
  }
}

module.exports = CommonController;
